<template>
  <div class="tenant-list">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="page-title">
        <h1>{{ $t('TenantManagement.Tenants') }}</h1>
        <p class="page-description">{{ $t('TenantManagement.TenantsDescription') }}</p>
      </div>
      <div class="page-actions">
        <el-button
          v-if="hasCreatePermission"
          type="primary"
          @click="showCreateDialog"
        >
          <el-icon><Plus /></el-icon>
          {{ $t('TenantManagement.CreateNew') }}
        </el-button>
        <el-button
          v-if="hasImportPermission"
          @click="showImportDialog"
        >
          <el-icon><Upload /></el-icon>
          {{ $t('TenantManagement.Import') }}
        </el-button>
        <el-button v-if="hasExportPermission" @click="handleExportCommand">
          <el-icon><Download /></el-icon>
          {{ $t('TenantManagement.Export') }}
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards" v-if="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.totalTenants }}</h3>
                <p>{{ $t('TenantManagement.TotalTenants') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.activeTenants }}</h3>
                <p>{{ $t('TenantManagement.ActiveTenants') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon inactive">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.inactiveTenants }}</h3>
                <p>{{ $t('TenantManagement.InactiveTenants') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon users">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.totalUsers }}</h3>
                <p>{{ $t('TenantManagement.TotalUsers') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item :label="$t('TenantManagement.Search')">
          <el-input
            v-model="searchForm.filter"
            :placeholder="$t('TenantManagement.SearchPlaceholder')"
            clearable
            @clear="handleSearch"
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('TenantManagement.Status')">
          <el-select
            v-model="searchForm.isActive"
            :placeholder="$t('TenantManagement.AllStatus')"
            clearable
            @change="handleSearch"
          >
            <el-option :label="$t('TenantManagement.Active')" :value="true" />
            <el-option :label="$t('TenantManagement.Inactive')" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('TenantManagement.IsDefault')">
          <el-select
            v-model="searchForm.isDefault"
            :placeholder="$t('TenantManagement.All')"
            clearable
            @change="handleSearch"
          >
            <el-option :label="$t('TenantManagement.Yes')" :value="true" />
            <el-option :label="$t('TenantManagement.No')" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            {{ $t('Common.Search') }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            {{ $t('Common.Reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 租户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>{{ $t('TenantManagement.TenantList') }}</span>
          <div class="table-actions">
            <el-tooltip :content="$t('Common.Refresh')">
              <el-button circle @click="loadTenants">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip :content="$t('Common.ColumnSettings')">
              <el-button circle @click="showColumnSettings">
                <el-icon><Setting /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tenants"
        stripe
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="name"
          :label="$t('TenantManagement.Name')"
          sortable="custom"
          min-width="150"
        >
          <template #default="{ row }">
            <div class="tenant-name">
              <el-avatar :size="32" :src="row.logo">
                {{ row.name.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="tenant-info">
                <div class="name">{{ row.name }}</div>
                <div class="display-name">{{ row.displayName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="keycloakRealm"
          :label="$t('TenantManagement.KeycloakRealm')"
          min-width="120"
        >
          <template #default="{ row }">
            <el-tag v-if="row.keycloakRealm" size="small">
              {{ row.keycloakRealm }}
            </el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="editionDisplayName"
          :label="$t('TenantManagement.Edition')"
          min-width="100"
        >
          <template #default="{ row }">
            <el-tag v-if="row.editionDisplayName" type="info" size="small">
              {{ row.editionDisplayName }}
            </el-tag>
            <span v-else class="text-muted">{{ $t('TenantManagement.Standard') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userCount"
          :label="$t('TenantManagement.UserCount')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-link
              v-if="row.userCount > 0"
              type="primary"
              @click="viewUsers(row.id)"
            >
              {{ row.userCount }}
            </el-link>
            <span v-else>0</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="isActive"
          :label="$t('TenantManagement.Status')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'" size="small">
              {{ row.isActive ? $t('TenantManagement.Active') : $t('TenantManagement.Inactive') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="isDefault"
          :label="$t('TenantManagement.Default')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.isDefault" type="warning" size="small">
              {{ $t('TenantManagement.Yes') }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creationTime"
          :label="$t('TenantManagement.CreationTime')"
          sortable="custom"
          width="180"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.creationTime) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('Common.Actions')"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip :content="$t('Common.View')">
                <el-button
                  size="small"
                  @click="viewTenant(row.id)"
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip :content="$t('Common.Edit')" v-if="hasUpdatePermission">
                <el-button
                  size="small"
                  type="primary"
                  @click="editTenant(row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-dropdown @command="(command) => handleTenantAction(command, row)">
                <el-button size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      command="permissions"
                      v-if="hasUpdatePermission"
                    >
                      <el-icon><Lock /></el-icon>
                      {{ $t('TenantManagement.ManagePermissions') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="sync"
                      v-if="hasSyncPermission"
                    >
                      <el-icon><Refresh /></el-icon>
                      {{ $t('TenantManagement.SyncUsers') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="health"
                      v-if="hasHealthCheckPermission"
                    >
                      <el-icon><Monitor /></el-icon>
                      {{ $t('TenantManagement.HealthCheck') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      :divided="true"
                      command="activate"
                      v-if="hasUpdatePermission && !row.isActive"
                    >
                      <el-icon><Check /></el-icon>
                      {{ $t('TenantManagement.Activate') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="deactivate"
                      v-if="hasUpdatePermission && row.isActive && !row.isDefault"
                    >
                      <el-icon><Close /></el-icon>
                      {{ $t('TenantManagement.Deactivate') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="delete"
                      v-if="hasDeletePermission && !row.isDefault"
                    >
                      <el-icon><Delete /></el-icon>
                      {{ $t('Common.Delete') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 批量操作栏 -->
    <div v-if="selectedTenants.length > 0" class="bulk-actions">
      <el-card>
        <div class="bulk-actions-content">
          <span>{{ $t('Common.Selected') }}: {{ selectedTenants.length }}</span>
          <div class="bulk-actions-buttons">
            <el-button
              v-if="hasUpdatePermission"
              @click="bulkActivate"
            >
              <el-icon><Check /></el-icon>
              {{ $t('TenantManagement.BulkActivate') }}
            </el-button>
            <el-button
              v-if="hasUpdatePermission"
              @click="bulkDeactivate"
            >
              <el-icon><Close /></el-icon>
              {{ $t('TenantManagement.BulkDeactivate') }}
            </el-button>
            <el-button
              v-if="hasDeletePermission"
              @click="showBulkOperationDialog"
            >
              <el-icon><Operation /></el-icon>
              {{ $t('Common.BulkOperation') }}
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 租户创建/编辑对话框 -->
    <TenantForm
      v-model="formDialogVisible"
      :tenant="editingTenant"
      @success="handleFormSuccess"
    />

    <!-- 权限管理对话框 -->
    <PermissionDialog
      v-model="permissionDialogVisible"
      entity-type="tenant"
      :entity-id="currentEntityId"
      :entity-name="currentEntityName"
      @success="handlePermissionSuccess"
    />

    <!-- 批量操作对话框 -->
    <BulkOperationDialog
      v-model="bulkOperationDialogVisible"
      entity-type="tenant"
      :selected-items="selectedTenants"
      @success="handleBulkOperationSuccess"
    />

    <!-- 导入导出对话框 -->
    <ImportExportDialog
      v-model="importDialogVisible"
      entity-type="tenant"
      :selected-items="selectedTenants"
      @success="handleImportExportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Upload, Download, Search, Refresh, Setting,
  OfficeBuilding, Check, Close, User, View, Edit, MoreFilled,
  Key, Monitor, Delete, Lock
} from '@element-plus/icons-vue'
import type { Tenant } from '@/types/abp'
import { tenantService } from '@/services/tenant.service'
import { permissionService } from '@/services/permission.service'
import { authService } from '@/services/AuthService'
import { abpService } from '@/services/abp.service'

// 导入子组件
import TenantForm from '@/components/tenants/TenantForm.vue'
import PermissionDialog from '@/components/common/PermissionDialog.vue'
import BulkOperationDialog from '@/components/common/BulkOperationDialog.vue'
import ImportExportDialog from '@/components/common/ImportExportDialog.vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tenants = ref<Tenant[]>([])
const statistics = ref<any>(null)
const selectedTenants = ref<Tenant[]>([])

// 搜索表单
const searchForm = reactive({
  filter: '',
  isActive: undefined,
  isDefault: undefined,
  sorting: '',
  skipCount: 0,
  maxResultCount: 20
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const formDialogVisible = ref(false)
const importDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const bulkOperationDialogVisible = ref(false)

// 编辑/查看的租户
const editingTenant = ref<Tenant | null>(null)
const currentEntityId = ref<string>('')
const currentEntityName = ref<string>('')

// 权限检查
const hasCreatePermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Create')
)
const hasUpdatePermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Update')
)
const hasDeletePermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Delete')
)
const hasImportPermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Import')
)
const hasExportPermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Export')
)
const hasFeaturePermission = computed(() =>
  abpService.hasPermission('TenantManagement.Features')
)
const hasSettingsPermission = computed(() =>
  abpService.hasPermission('TenantManagement.Settings')
)
const hasKeycloakPermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Keycloak')
)
const hasSyncPermission = computed(() =>
  abpService.hasPermission('TenantManagement.Tenants.Sync')
)
const hasHealthCheckPermission = computed(() =>
  abpService.hasPermission('TenantManagement.HealthCheck')
)

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadStatistics(),
    loadTenants()
  ])
})

// 方法
const loadStatistics = async () => {
  try {
    statistics.value = await tenantService.getTenantStatistics()
  } catch (error) {
    console.error('加载租户统计失败:', error)
  }
}

const loadTenants = async () => {
  try {
    loading.value = true

    const params = {
      ...searchForm,
      skipCount: (pagination.page - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    }

    const result = await tenantService.getTenants(params)
    tenants.value = result.items
    pagination.total = result.totalCount
  } catch (error) {
    console.error('加载租户列表失败:', error)
    ElMessage.error('加载租户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadTenants()
}

const handleReset = () => {
  Object.assign(searchForm, {
    filter: '',
    isActive: undefined,
    isDefault: undefined
  })
  pagination.page = 1
  loadTenants()
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  if (order) {
    searchForm.sorting = `${prop} ${order === 'ascending' ? 'asc' : 'desc'}`
  } else {
    searchForm.sorting = ''
  }
  loadTenants()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadTenants()
}

const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadTenants()
}

const handleSelectionChange = (selection: Tenant[]) => {
  selectedTenants.value = selection
}

// 操作方法
const showCreateDialog = () => {
  editingTenant.value = null
  formDialogVisible.value = true
}

const showImportDialog = () => {
  importDialogVisible.value = true
}

const showBulkOperationDialog = () => {
  bulkOperationDialogVisible.value = true
}

const showColumnSettings = () => {
  ElMessage.info('列设置功能开发中...')
}

const viewTenant = (id: string) => {
  viewingTenantId.value = id
  detailDialogVisible.value = true
}

const editTenant = (tenant: Tenant) => {
  editingTenant.value = { ...tenant }
  formDialogVisible.value = true
}

const viewUsers = (tenantId: string) => {
  router.push({
    name: 'Users',
    query: { tenantId }
  })
}

const handleTenantAction = async (command: string, tenant: Tenant) => {
  switch (command) {
    case 'permissions':
      currentEntityId.value = tenant.id
      currentEntityName.value = tenant.name
      permissionDialogVisible.value = true
      break
    case 'sync':
      await syncUsers(tenant.id)
      break
    case 'health':
      await performHealthCheck(tenant.id)
      break
    case 'activate':
      await activateTenant(tenant.id)
      break
    case 'deactivate':
      await deactivateTenant(tenant.id)
      break
    case 'delete':
      await deleteTenant(tenant)
      break
  }
}

const syncUsers = async (tenantId: string) => {
  try {
    const result = await tenantService.syncKeycloakUsers(tenantId)
    ElMessage.success(`同步完成: ${result.syncedCount} 个用户同步成功`)
    loadStatistics()
  } catch (error) {
    ElMessage.error('用户同步失败')
  }
}

const performHealthCheck = async (tenantId: string) => {
  try {
    const result = await tenantService.performTenantHealthCheck(tenantId)

    const status = result.status === 'Healthy' ? 'success' :
                  result.status === 'Degraded' ? 'warning' : 'error'

    ElMessage({
      message: `健康检查完成: ${result.status}`,
      type: status
    })
  } catch (error) {
    ElMessage.error('健康检查失败')
  }
}

const activateTenant = async (tenantId: string) => {
  try {
    await tenantService.activateTenant(tenantId)
    ElMessage.success('租户激活成功')
    loadTenants()
    loadStatistics()
  } catch (error) {
    ElMessage.error('租户激活失败')
  }
}

const deactivateTenant = async (tenantId: string) => {
  try {
    await tenantService.deactivateTenant(tenantId)
    ElMessage.success('租户停用成功')
    loadTenants()
    loadStatistics()
  } catch (error) {
    ElMessage.error('租户停用失败')
  }
}

const deleteTenant = async (tenant: Tenant) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除租户 "${tenant.displayName}" 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await tenantService.deleteTenant(tenant.id)
    ElMessage.success('租户删除成功')
    loadTenants()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('租户删除失败')
    }
  }
}


// 导出功能
const handleExportCommand = () => {
  importDialogVisible.value = true
}

// 事件处理
const handleFormSuccess = () => {
  loadTenants()
  loadStatistics()
}

const handlePermissionSuccess = () => {
  ElMessage.success('权限更新成功')
  permissionDialogVisible.value = false
}

const handleBulkOperationSuccess = () => {
  loadTenants()
  selectedTenants.value = []
  bulkOperationDialogVisible.value = false
}

const handleImportExportSuccess = (result: any) => {
  if (result.type === 'import') {
    loadTenants()
    loadStatistics()
  }
  importDialogVisible.value = false
  ElMessage.success(`${result.type === 'import' ? '导入' : '导出'}完成`)
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.tenant-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.page-actions {
  display: flex;
  gap: 12px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-icon.inactive {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.stat-icon.users {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.stat-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.tenant-name {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tenant-info .name {
  font-weight: 500;
  color: #333;
}

.tenant-info .display-name {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.text-muted {
  color: #999;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.bulk-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.bulk-actions-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.bulk-actions-buttons {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .page-actions {
    justify-content: center;
  }

  .statistics-cards .el-col {
    margin-bottom: 16px;
  }

  .search-card .el-form {
    flex-direction: column;
  }

  .search-card .el-form-item {
    margin-bottom: 16px;
    margin-right: 0;
  }

  .bulk-actions {
    position: static;
    transform: none;
    margin-bottom: 20px;
  }
}
</style>